package jsp.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.Revision;
import jsp.classes.Session;

/**
 * @author Remco Haszing
 */
public class Download extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request, response);
    }

    /**
     * Downloads a file from the server. This method searches the item
     * corresponding to the p, i and r parameters of a HttpServletRequest and
     * returns this file to the browser.
     *
     * @param request The request that should contain the right parameters and
     * session.
     * @param response The response to which a file will be sent.
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {            
            Session session = (Session) request.getSession(true).getAttribute("user");
            long p = Long.parseLong(request.getParameter("p"));
            long i = Long.parseLong(request.getParameter("i"));
            int r = Integer.parseInt(request.getParameter("r"));
            File file = new File(session.getUploadDir() + p + "/" + i + "/" + r);
            Revision rev = session.findProjectItemById(p, i).getRevision(r);
            response.setContentLength((int) file.length());
            response.setContentType(rev.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + rev.getFilename());
            byte[] b = new byte[(int) file.length()];
            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
            buf.read(b);
            buf.close();
            ServletOutputStream stream = response.getOutputStream();
            stream.write(b);
            stream.flush();
            stream.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
